import { createTopic } from '~/server/database/services/topicService'
import { TopicDomain, Difficulty, type TopicCreationAttributes } from '~/server/database/models/Topic'
import authMiddleware from '~/server/middleware/auth'

export default defineEventHandler(async (event) => {
  try {
    // 使用认证中间件获取用户信息
    await authMiddleware(event)
    
    const body = await readBody(event)
    
    // 验证必填字段
    const { title, domain, difficulty, standardAnswer, description } = body
    
    if (!title || !domain || !difficulty || !standardAnswer) {
      throw createError({
        statusCode: 400,
        statusMessage: '缺少必填字段'
      })
    }

    // 验证枚举值
    if (!Object.values(TopicDomain).includes(domain)) {
      throw createError({
        statusCode: 400,
        statusMessage: '无效的领域值'
      })
    }

    if (!Object.values(Difficulty).includes(difficulty)) {
      throw createError({
        statusCode: 400,
        statusMessage: '无效的难度值'
      })
    }

    // 从event.context中获取用户信息
    const user = event.context.user
    
    // 创建题目数据
    const topicData = {
      title,
      domain,
      difficulty,
      standardAnswer,
      submitterId: user.id,
      description: description || '',
      reviewStatus: 'PENDING'
    }

    // 创建题目
    const topic = await createTopic(topicData as TopicCreationAttributes)

    return {
      success: true,
      data: topic,
      message: '题目创建成功'
    }
  } catch (error) {
    console.error('创建题目失败:', error)
    
    if (error && typeof error === 'object' && 'statusCode' in error) {
      throw error
    }
    
    throw createError({
      statusCode: 500,
      statusMessage: '创建题目失败'
    })
  }
})
